/**
 * 用户管理状态
 * 管理用户列表、分页、增删改查等功能
 */

import { defineStore } from 'pinia'
import { ref } from 'vue'
import type { User, UserQuery, UserForm, PaginationConfig } from '@/types'
import { getUserList, addUser, updateUser, deleteUser, batchDeleteUser } from '@/api'
import { message } from 'ant-design-vue'

export const useUserStore = defineStore('user', () => {
  // 状态
  const list = ref<User[]>([])
  const total = ref<number>(0)
  const loading = ref<boolean>(false)
  const pagination = ref<PaginationConfig>({
    current: 1,
    pageSize: 10,
    total: 0,
    showSizeChanger: true,
    showQuickJumper: true,
    showTotal: (total: number) => `共 ${total} 条`,
  })

  // 查询参数
  const queryParams = ref<UserQuery>({
    page: 1,
    pageSize: 10,
    keyword: '',
    role: undefined,
    status: undefined,
    sortField: undefined,
    sortOrder: undefined,
  })

  /**
   * 获取用户列表
   */
  async function fetchUserList(params?: Partial<UserQuery>): Promise<void> {
    try {
      loading.value = true

      // 合并查询参数
      const mergedParams = { ...queryParams.value, ...params }
      queryParams.value = mergedParams

      const res = await getUserList(mergedParams)

      if (res.success && res.data) {
        list.value = res.data.list
        total.value = res.data.total

        // 更新分页信息
        pagination.value.current = mergedParams.page || 1
        pagination.value.pageSize = mergedParams.pageSize || 10
        pagination.value.total = res.data.total
      } else {
        message.error(res.message || '获取用户列表失败')
      }
    } catch (error: any) {
      message.error(error.message || '获取用户列表失败')
    } finally {
      loading.value = false
    }
  }

  /**
   * 添加用户
   */
  async function addUserItem(form: UserForm): Promise<boolean> {
    try {
      const res = await addUser(form)

      if (res.success) {
        message.success(res.message || '添加成功')
        // 重新加载列表
        await fetchUserList()
        return true
      } else {
        message.error(res.message || '添加失败')
        return false
      }
    } catch (error: any) {
      message.error(error.message || '添加失败')
      return false
    }
  }

  /**
   * 更新用户
   */
  async function updateUserItem(id: number, form: UserForm): Promise<boolean> {
    try {
      const res = await updateUser(id, form)

      if (res.success) {
        message.success(res.message || '更新成功')
        // 重新加载列表
        await fetchUserList()
        return true
      } else {
        message.error(res.message || '更新失败')
        return false
      }
    } catch (error: any) {
      message.error(error.message || '更新失败')
      return false
    }
  }

  /**
   * 删除用户
   */
  async function deleteUserItem(id: number): Promise<boolean> {
    try {
      const res = await deleteUser(id)

      if (res.success) {
        message.success(res.message || '删除成功')
        // 重新加载列表
        await fetchUserList()
        return true
      } else {
        message.error(res.message || '删除失败')
        return false
      }
    } catch (error: any) {
      message.error(error.message || '删除失败')
      return false
    }
  }

  /**
   * 批量删除用户
   */
  async function batchDeleteUserItems(ids: number[]): Promise<boolean> {
    try {
      const res = await batchDeleteUser(ids)

      if (res.success) {
        message.success(res.message || '批量删除成功')
        // 重新加载列表
        await fetchUserList()
        return true
      } else {
        message.error(res.message || '批量删除失败')
        return false
      }
    } catch (error: any) {
      message.error(error.message || '批量删除失败')
      return false
    }
  }

  /**
   * 重置查询参数
   */
  function resetQuery(): void {
    queryParams.value = {
      page: 1,
      pageSize: 10,
      keyword: '',
      role: undefined,
      status: undefined,
      sortField: undefined,
      sortOrder: undefined,
    }
  }

  /**
   * 刷新列表
   */
  async function refresh(): Promise<void> {
    await fetchUserList()
  }

  return {
    // 状态
    list,
    total,
    loading,
    pagination,
    queryParams,

    // 方法
    fetchUserList,
    addUserItem,
    updateUserItem,
    deleteUserItem,
    batchDeleteUserItems,
    resetQuery,
    refresh,
  }
})
